<template>
  <div class="page-container">
    <div class="header-section">
<!--      <div class="header-badge">新品上市</div>-->
      <h1 class="header-title">助农直播 · 新鲜直达</h1>
      <p class="header-subtitle">从田间到餐桌，原产地直供，助力乡村振兴</p>
<!--      <div class="header-action">
        <el-button type="primary" size="large" round @click="router.push('/live/all')">
          <i class="el-icon-video-play"></i> 查看全部直播
        </el-button>
      </div>-->
    </div>

    <div class="content-container">
      <el-row :gutter="20" class="live-grid">
        <el-col
            :xs="24" :sm="12" :md="8" :lg="6"
            v-for="(item, index) in liveRoom"
            :key="index"
            class="live-card-col"
        >
          <el-card
              class="live-card"
              :body-style="{ padding: '0' }"
              shadow="hover"
              @click="viewLiveDetail(liveRoom[index].id,liveRoom[index].liveTitle, liveRoom[index].streamKey)"
          >
            <div class="card-media">
              <div class="video-container">
                <video
                    class="video-js"
                    :ref="el => videoPlayers[index] = el"
                    muted
                    playsinline
                    style="background-color:rgb(18,9,37);width: 100%;height: 100%;"
                ></video>
                <div class="video-overlay">
                  <div class="play-button">
                    <i class="el-icon-video-play"></i>
                  </div>
                </div>
              </div>
              <div class="card-tags">
                <el-tag v-if="item.isNew" type="success" size="small" effect="plain">新品</el-tag>
                <el-tag v-if="item.isHot" type="danger" size="small" effect="plain">热门</el-tag>
              </div>
            </div>

            <div class="card-content">
              <h3 class="card-title">{{ item.liveTitle }}</h3>
              <p class="card-desc">{{ item.description }}</p>
              <div class="card-footer">
                <div class="avatar-group">
                  <el-avatar
                      v-for="(avatar, i) in item.avatars"
                      :key="i"
                      :size="24"
                      :src="avatar"
                      class="avatar"
                  ></el-avatar>
                </div>
                <span class="view-count">
                  <i class="el-icon-view"></i> {{ item.viewCount || 0 }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import { onMounted, ref, watch, nextTick, onUnmounted } from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();
// 查看直播详情
const viewLiveDetail = (liveId,liveTitle,streamKey) => {
  router.push({
    path: '/live/de',
    query: {
      id: liveId,
      liveTitle: liveTitle,
      streamKey: streamKey
    }
  });
};

const liveRoom = ref([]);
// 使用数组来存储所有播放器实例
const videoPlayers = ref([]);
const playerInstances = ref([]);

const getLiveRoom = () => {
  axios.get(BASE_URL+'/api/v1/live/rooms')
      .then((response)=>{
        if (response.data.code == 2000){
          // 添加模拟数据用于展示
          liveRoom.value = response.data.data.map((item, index) => ({
            ...item,
            isNew: index % 3 === 0,
            isHot: index % 5 === 0,
            viewCount: Math.floor(Math.random() * 1000) + 500,
            avatars: [
              'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
              'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
              'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
            ].slice(0, index % 3 + 1)
          }));
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(() => {
        // 模拟数据用于开发
        liveRoom.value = Array.from({length: 8}, (_, i) => ({
          id: i + 1,
          liveTitle: `第${i+1}农场直播 - 新鲜水果采摘`,
          description: `来自${['阳光农场', '绿野庄园', '丰收果园', '田园牧歌'][i%4]}的实时直播，观看${['苹果', '草莓', '橙子', '葡萄'][i%4]}采摘过程`,
          streamKey: `https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8`,
          isNew: i % 3 === 0,
          isHot: i % 5 === 0,
          viewCount: Math.floor(Math.random() * 1000) + 500,
          avatars: [
            'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
            'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
          ].slice(0, i % 3 + 1)
        }));
      });
};

// 初始化所有播放器
const initPlayers = () => {
  // 先销毁所有现有的播放器
  playerInstances.value.forEach(player => {
    if (player) player.dispose();
  });

  // 重置播放器实例数组
  playerInstances.value = [];

  // 为每个视频元素初始化播放器
  videoPlayers.value.forEach((playerEl, index) => {
    if (playerEl && liveRoom.value[index]) {
      const player = videojs(playerEl, {
        autoplay: true,
        controls: true,
        controlBar: {
          pictureInPictureToggle: false,
          fullscreenToggle: true
        },
        sources: [{
          src: liveRoom.value[index].streamKey,
          type: 'application/x-mpegURL'
        }]
      }, () => {
        console.log(`播放器 ${index} 加载完成`);
      });

      playerInstances.value[index] = player;
    }
  });
};

onMounted(() => {
  getLiveRoom();
});

// 当liveRoom数据变化时初始化播放器
watch(liveRoom, (newVal) => {
  if (newVal.length > 0) {
    // 使用nextTick确保DOM已更新
    nextTick(() => {
      initPlayers();
    });
  }
}, { deep: true });

// 组件卸载时销毁所有播放器
onUnmounted(() => {
  playerInstances.value.forEach(player => {
    if (player) player.dispose();
  });
});
</script>

<style scoped>
.page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.header-section {
  text-align: center;
  margin: 60px 0 40px;
  padding: 40px 0;
  position: relative;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header-badge {
  display: inline-block;
  background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.header-title {
  font-size: 2.5rem;
  color: #2c3e50;
  margin-bottom: 15px;
  font-weight: 700;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #2c3e50, #4ca1af);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-subtitle {
  font-size: 1.2rem;
  color: #7f8c8d;
  max-width: 700px;
  margin: 0 auto 25px;
  line-height: 1.6;
}

.header-action {
  margin-top: 25px;
}

.content-container {
  padding: 20px 0 60px;
}

.live-grid {
  margin-bottom: -20px;
}

.live-card-col {
  margin-bottom: 20px;
}

.live-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  border: none;
  cursor: pointer;
}

.live-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-media {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 Aspect Ratio */
  overflow: hidden;
}

.video-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.video-js {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  opacity: 0;
}

.live-card:hover .video-overlay {
  opacity: 1;
}

.play-button {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.play-button i {
  color: #4ca1af;
  font-size: 24px;
  margin-left: 4px;
}

.card-tags {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  z-index: 2;
}

.card-content {
  padding: 20px;
}

.card-title {
  font-size: 1.1rem;
  color: #2c3e50;
  margin-bottom: 10px;
  font-weight: 600;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 48px;
}

.card-desc {
  font-size: 0.9rem;
  color: #7f8c8d;
  margin-bottom: 15px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 48px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.avatar-group {
  display: flex;
  align-items: center;
}

.avatar {
  margin-right: -8px;
  border: 2px solid white;
  transition: all 0.3s ease;
}

.avatar:hover {
  transform: scale(1.1);
  z-index: 2;
}

.view-count {
  font-size: 0.85rem;
  color: #95a5a6;
  display: flex;
  align-items: center;
}

.view-count i {
  margin-right: 5px;
  font-size: 14px;
}

@media (max-width: 768px) {
  .header-title {
    font-size: 2rem;
  }

  .header-subtitle {
    font-size: 1rem;
  }

  .live-card-col {
    padding: 0 5px;
  }

  .card-content {
    padding: 15px;
  }

  .card-title {
    font-size: 1rem;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.live-card-col {
  animation: fadeIn 0.6s ease forwards;
  opacity: 0;
}

.live-card-col:nth-child(1) { animation-delay: 0.1s; }
.live-card-col:nth-child(2) { animation-delay: 0.2s; }
.live-card-col:nth-child(3) { animation-delay: 0.3s; }
.live-card-col:nth-child(4) { animation-delay: 0.4s; }
.live-card-col:nth-child(5) { animation-delay: 0.5s; }
.live-card-col:nth-child(6) { animation-delay: 0.6s; }
.live-card-col:nth-child(7) { animation-delay: 0.7s; }
.live-card-col:nth-child(8) { animation-delay: 0.8s; }
</style>